<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage,2016-04-14 14:16
// +----------------------------------------------------------------------

namespace Admin\Controller;

class TestController extends BaseController
{

    function __construct() {
        parent::__construct();

//        exit('已关闭'); //关闭
    }

    public function index()
    {
        if(I('get.key')!='1234567890'){
            exit('已关闭'); //关闭
        }
        $this->display();
    }

    function import_rent(){
//        ini_set('memory_limit','512M');
//        set_time_limit(0);
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['xls' , 'xlsx'];// 设置附件上传类型
        $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = FALSE;
        // 上传文件
        if($_FILES['excel']['name'] != ''){
            $info = $upload->upload();
            if (!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
            } else {// 上传成功
                $Order = M('book');
                $Order->startTrans();
                $filepath = $upload->rootPath . $info["excel"]["savename"];
            }
        }else {
            $filepath=I('post.filename');
        }
        if($filepath==''){
            $this->error('路径文件错误');
        }
        $Order = M('Order_book');
        $OrderBook = M('Order_has_book');
        $Card=M('Card');
        $Book=M('Book');
        $Pay=M('Pay');
        $Return=M('Order_book_return');
        $Error=new \Common\Model\ErrorModel();

        $Order->startTrans();
        $data = excel_import($filepath,'xls');
        //第一行为字段
        $colname = $data[0];
        unset($data[0]);
        $line=0;
        foreach ($data as $k => $v) {
            $line++;
            $data_row=$v;
            foreach($colname as $kk=>$vv){
                if((string)$data_row[$kk]==''){
                    continue;
                }
                switch($vv){
                    case 'return_time':
                    case 'create_time':$save[ $vv ]=convert_etimetoptime($data_row[ $kk ]);break;
                    default:$save[$vv]=$data_row[$kk];break;
                }

            }
            if(sizeof($save)==0){
                continue;
            }
            echo '第'.$line.'行,'.$save['card_id'].',id:'.$save['id'];
            //获取用户信息:user_id
            $dc=$Card->where(['card_id'=>$save['card_id']])->find();
            $db=$Book->where(['spbs'=>$save['spbs']])->find();
            if(!$db){
                $error='批量导入借阅记录,错误问题:spbs不存在,此spbs为:'.$save['spbs'];
                echo ' 图书spbs不存在 <br>';
                $Error->log($error);
                continue;
                $Order->rollback();
                //                return;
            }
            $data_pay['user_id']=$dc['user_id'];
            $data_pay['status']=1;
            $data_pay['type']=1;
            $data_pay['summary']='初始化批量导入,借阅数据导入';
            $data_pay['money']=0;
            $data_pay['money_real']=0;
            $data_pay['money_zero']=0;;
            $data_pay['create_time']=$save['create_time'];

            //生成支付订单
            $pay_id=$Pay->data($data_pay)->add();
            if(!$pay_id){
                $Order->rollback();
                echo '生成支付订单错误';
                return;
            }
            //生成订单
            $data_order['user_id']=$dc['user_id'];
            $data_order['money']=0;
            $data_order['price_freight']=0;
            $data_order['type']=1;
            $data_order['address']=urldecode(json_encode(['info'=>'批量导入借阅记录'],JSON_UNESCAPED_UNICODE));
            $data_order['state_order']=3;
            $data_order['pay_id']=$pay_id;
            $data_order['create_time']=$save['create_time'];

            $order_id=$Order->data($data_order)->add();
            if(!$order_id){
                $Order->rollback();
                echo '生成借阅订单错误';
                return;
            }
            //添加订单图书
            $data_book['order_id']=$order_id;
            $data_book['book_id']=$db['book_id'];
            $data_book['quantity']=1;
            $data_book['type']=1;
            $data_book['is_backed']=1-$save['state']; //state,1:借（未归还）;0:还（已归还）
            if($save['state']==0){
                //已归还
                $data_book['num_backed']=$data_book['quantity'];
                //记录归还记录
                $dreturn=[
                    "order_id"=>$order_id,
                    "book_id"=>$db['book_id'],
                    'user_id'=>$dc['user_id'],
                    'create_time'=>$save['return_time']
                ];
                $return_id=$Return->add($dreturn);
                if(!$return_id){
                    $Order->rollback();
                    echo '记录还书记录失败';
                    return;
                }
            }
            $orderbook_id=$OrderBook->data($data_book)->add();
            if(!$orderbook_id){
                $Order->rollback();
                echo '生成订单图书错误';
                return;
            }
            echo '    成功'.'<br>';
            unset($data[$k]);
        }
        $Order->commit();
        echo '<br>解析成功';
    }

    function checkPic(){
        $Book=M('Book');
        $num=10;
        $c=$Book->count();
        $total=0;
        for($i=0;$i<=$c;$i+=$num){
            $d=$Book->limit($i,$num)->field('book_id,spbs')->order('book_id')->select();
            foreach($d as $k=>$v){
                $picpath='/mnt/www/html/xsc/public/uploads/book/'.$v['spbs'].'-fm.jpg';
                if(file_exists($picpath)){
                    echo $picpath.'-'.$v['book_id'].'存在:'.$v['spbs'].'<br>';
                    $b_logo='/uploads/book/'.$v['spbs'].'-fm.jpg';
                }else{
                    echo $picpath.'-'.$v['book_id'].'不存在:'.$v['spbs'].'<br>';
                    $b_logo='';
                }
                $Book->where(['book_id'=>$v['book_id']])->data(['b_logo'=>$b_logo])->save();
                $total++;
            }
//            exit();
        }
        echo '共处理:'.$total;
    }
    
    function exportExcel(){
        $field='book_id,spbs,isbn,tm,sm,b_logo';
        $map=[
            'b_logo'=>''
        ];
        $d=M('Book')->where($map)->field($field)->select();
        $file = excel_export($d);
        ouput_Browser($file);
    }
    //通用导入数据
    function  importData(){

        $data=$this->getExcelData('uploads/excel/isbn.xls');
        $r=$this->isbnImport($data);
        if($r){
            echo '<br>SUCCESS';
        }else{
            echo '<br>ERROR';
        }
    }

    function getExcelData($excelpath){
        $data = excel_import($excelpath,'xls');
        return $data;
    }
    //isbn导入数据
    function isbnImport($data){
        $model=M('Book');
        $model->startTrans();
        //第一行为字段
        $colname = $data[0];
        unset($data[0]);
        $line=0;
        foreach ($data as $k => $v) {
            $line++;
            $data_row=$v;
            foreach($colname as $kk=>$vv){
                if((string)$data_row[$kk]==''){
                    continue;
                }
                switch($vv){
                    case 'return_time':
                    case 'create_time':$save[ $vv ]=convert_etimetoptime($data_row[ $kk ]);break;
                    default:$save[$vv]=$data_row[$kk];break;
                }

            }
            if(sizeof($save)==0){
                continue;
            }
            echo '第'.$line.'行,'.$save['SPBS'];
            $model->where(['spbs'=>$save['SPBS']])->data(['isbn'=>$save['ISBN']])->save();
            echo '    成功'.'<br>';
            unset($data[$k]);
        }
        $model->commit();
        return true;
    }
    //清除缓存
    function clearCache(){
        //清除首页推荐图书列表
        S('Index_index_booklists',null);
        echo '首页推荐图书缓存清除成功';
    }
}